package com.fili.util;

import com.fili.util.DEBUG;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Fili
 * Date: Mar 10, 2007
 * Time: 4:09:02 PM
 */
public class EditConfig
{
    private static EditConfig instance;
    private ArrayList<ConfigProperty> properties;


    public static EditConfig getInstance()
    {
        return instance;
    }

    private EditConfig()
    {
        properties = new ArrayList<ConfigProperty>();
    }

    private ConfigProperty find(String name)
    {
        for (ConfigProperty cf : properties)
            if (cf.name.equals(name))
                return cf;

        return null;
    }

    public double getProperty(String name)
    {
        ConfigProperty cf = find(name);
        if (cf != null)
            return cf.value;

        return 0;
    }

    public void setProperty(String name, double value)
    {
        ConfigProperty cf = find(name);
        if (cf != null)
            cf.value = value;
        else
        {
            cf = new ConfigProperty(name, value);
            properties.add(cf);
        }
    }

    public void load(String fname)
    {
        try
        {
            BufferedReader br = new BufferedReader(new FileReader(fname));

            String line;

            while ((line = br.readLine()) != null)
            {
                line = line.trim();
                if (line.length() > 0)
                {
                    String[] items = line.split("\\s+");
                    if (items.length != 2)
                        return;

                    String name = items[0];
                    double value = Double.parseDouble(items[1]);
                    setProperty(name, value);
                }
            }

        }
        catch (Exception e)
        {
            DEBUG.ex(e);
        }
    }

    public void save(String fname)
    {
        try
        {
            FileOutputStream fos = new FileOutputStream(fname);
            for (ConfigProperty cf : properties)
            {
                String s = cf.name + "\t\t" + cf.value + "\n";
                fos.write(s.getBytes());
            }
            fos.close();
        }
        catch (Exception e)
        {
            DEBUG.ex(e);
        }

    }

    static
    {
        instance = new EditConfig();
    }

    public class ConfigProperty
    {
        String name;
        double value;


        public ConfigProperty(String name, double value)
        {
            this.name = name;
            this.value = value;
        }
    }

}
